<template>
  <div style="text-align: center">
    <a-spin dot :hide-icon="!isLoading" />
  </div>
  <div v-show="!isLoading">
    <div id="rankingListView">
      <a-table
        :columns="rankingListColumns"
        :data="rankingList"
        :pagination="false"
        :column-resizable="true"
        :bordered="false"
        :stripe="true"
      >
        <template #user="{ record, rowIndex }">
          <a-space>
            <div>
              <a-tag checkable size="large" color="#fedcba"
                ><b
                  ><i>{{ rowIndex + 1 }}</i></b
                >
              </a-tag>
            </div>
            <div>
              <a-avatar>
                <img alt="avatar" :src="record.userAvatar" />
              </a-avatar>
            </div>
            <div>
              <div>
                {{ record.userName }}
              </div>
              <div>
                <i>
                  已完成题数
                  <b> {{ JSON.parse(record.completedQuestion).length }}</b
                  >题
                </i>
              </div>
            </div>
          </a-space>
        </template>
      </a-table>
    </div>
    <div id="questionsView">
      <a-form :model="searchParams" layout="inline">
        <a-form-item field="title" label="名称" style="min-width: 240px">
          <a-input v-model="searchParams.title" placeholder="请输入名称" />
        </a-form-item>
        <a-form-item field="tags" label="标签" style="min-width: 240px">
          <a-input-tag v-model="searchParams.tags" placeholder="请输入标签" />
        </a-form-item>
        <a-form-item>
          <a-button type="primary" @click="doSubmit">提交</a-button>
        </a-form-item>
      </a-form>
      <a-divider size="0" />
      <a-table
        :ref="tableRef"
        :columns="columns"
        :data="dataList"
        :pagination="{
          showTotal: true,
          pageSize: searchParams.pageSize,
          current: searchParams.current,
          total,
        }"
        @page-change="onPageChange"
      >
        <template #completed="{ record }">
          <a-space wrap>
            <a-button v-if="record.completed == 'passed'">
              <template #icon>
                <icon-check-circle-fill size="28" strokeWidth="2" />
              </template>
            </a-button>
            <a-button v-if="record.completed == 'not_passed'">
              <template #icon>
                <icon-check-circle size="28" strokeWidth="2" />
              </template>
            </a-button>
          </a-space>
        </template>
        <template #tags="{ record }">
          <a-space wrap>
            <a-tag
              v-for="(tag, index) of record.tags"
              :key="index"
              color="green"
              >{{ tag }}
            </a-tag>
          </a-space>
        </template>
        <template #acceptedRate="{ record }">
          {{
            `${
              record.submitNum
                ? ((record.acceptedNum / record.submitNum) * 100).toFixed(2)
                : "0.00"
            }% (${record.acceptedNum}/${record.submitNum})`
          }}
        </template>
        <template #createTime="{ record }">
          {{ moment(record.createTime).format("YYYY-MM-DD HH:mm:ss") }}
        </template>
        <template #optional="{ record }">
          <a-space>
            <a-button type="primary" @click="toQuestionPage(record)">
              做题
            </a-button>
          </a-space>
        </template>
      </a-table>
    </div>
  </div>
</template>

<script setup lang="ts">
import { defineComponent, onMounted, ref, watchEffect } from "vue";
import {
  Question,
  QuestionControllerService,
  QuestionQueryRequest,
  UserControllerService,
} from "../../../generated";
import message from "@arco-design/web-vue/es/message";
import { useRouter } from "vue-router";
import moment from "moment";
import {
  IconCheckCircle,
  IconCheckCircleFill,
} from "@arco-design/web-vue/es/icon";

const components = {
  IconCheckCircle,
  IconCheckCircleFill,
};

defineComponent({
  components,
});
const tableRef = ref();

const isLoading = ref(true);

const dataList = ref([]);
const rankingList = ref([]);
const total = ref(0);
const searchParams = ref<QuestionQueryRequest>({
  title: "",
  tags: [],
  pageSize: 10,
  current: 1,
});

const loadData = async () => {
  const res = await QuestionControllerService.listQuestionVoByPageUsingPost(
    searchParams.value
  );
  if (res.code === 40100) {
    router.push("/user/login");
  }
  const resp = await UserControllerService.getTopUsersUsingGet(10);
  if (res.code === 0 && resp.code === 0) {
    isLoading.value = false;
    dataList.value = res.data.records;
    rankingList.value = resp.data?.reverse();
    total.value = res.data.total;
  } else {
    message.error("加载失败，" + res.message);
  }
};

/**
 * 监听 searchParams 变量，改变时触发页面的重新加载
 */
watchEffect(() => {
  loadData();
});

/**
 * 页面加载时，请求数据
 */
onMounted(() => {
  loadData();
});

// {id: "1", title: "A+ D", content: "新的题目内容", tags: "["二叉树"]", answer: "新的答案", submitNum: 0,…}

const columns = [
  {
    title: "",
    slotName: "completed",
  },
  {
    title: "题号",
    dataIndex: "id",
  },
  {
    title: "题目名称",
    dataIndex: "title",
  },
  {
    title: "标签",
    slotName: "tags",
  },
  {
    title: "通过率",
    slotName: "acceptedRate",
  },
  {
    title: "创建时间",
    slotName: "createTime",
  },
  {
    slotName: "optional",
  },
];
const rankingListColumns = [
  {
    title: "排行榜",
    slotName: "user",
  },
];
const onPageChange = (page: number) => {
  isLoading.value = true;
  searchParams.value = {
    ...searchParams.value,
    current: page,
  };
};

const router = useRouter();

/**
 * 跳转到做题页面
 * @param question
 */
const toQuestionPage = (question: Question) => {
  router.push({
    path: `/view/question/${question.id}`,
  });
};

/**
 * 确认搜索，重新加载数据
 */
const doSubmit = () => {
  // 这里需要重置搜索页号
  searchParams.value = {
    ...searchParams.value,
    current: 1,
  };
};
</script>

<style scoped>
#questionsView {
  max-width: 1080px;
  margin: 0 auto;
}

#rankingListView {
  position: absolute;
  right: 88px;
  padding-top: 60px;
  width: 300px;
}
</style>
